package com.jyhs.maven.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("CorsFilter init");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("CorsFilter 过滤操作，设置跨域请求头");



        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        resp.setCharacterEncoding("utf-8");

        resp.setHeader("Access-Control-Allow-Origin", "*");

        resp.setHeader("Access-Control-Allow-Credentials", "true");
        // 设置允许的方法
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        // 预检请求的有效期
        resp.setHeader("Access-Control-Max-Age", "3600");
        // 设置允许的Header
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,content-type");

        // 过滤器链继续执行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
